#!/bin/sh

set -eu

# Install provision map
if [ -f "$IGconf_image_pmapfile" ] ; then
   cp ${IGconf_image_pmapfile} ${IGconf_image_outputdir}/provisionmap.json
else
   die "No pmap. Unable to provision image."
fi


# Generate pre-defined UUIDs
BOOT_LABEL=$(uuidgen | sed 's/-.*//' | tr 'a-f' 'A-F')
BOOT_UUID=$(echo "$BOOT_LABEL" | sed 's/^\(....\)\(....\)$/\1-\2/')
SYSTEM_UUID=$(uuidgen)
CRYPT_UUID=$(uuidgen)

rm -f ${IGconf_image_outputdir}/img_uuids
for v in BOOT_LABEL BOOT_UUID SYSTEM_UUID CRYPT_UUID; do
    eval "val=\$$v"
    echo "$v=$val" >> "${IGconf_image_outputdir}/img_uuids"
done


# Populate PMAP UUIDs
sed -i \
   -e "s|<BOOT_UUID>|$BOOT_UUID|g" \
   -e "s|<SYSTEM_UUID>|$SYSTEM_UUID|g" \
   -e "s|<CRYPT_UUID>|$CRYPT_UUID|g" ${IGconf_image_outputdir}/provisionmap.json


# Generate slot map. IDP does preserve GPT labels but this has yet make it to
# mainline. Add the map as a fallback so a provisioned image boots.
pmap --schema "$IGconf_image_pmap_schema" \
     --file "${IGconf_image_outputdir}/provisionmap.json" \
     --slotvars > "$1/boot/slot.map"


# Hint to initramfs-tools we have an ext4 rootfs
sed -i "s|FSTYPE=\([^ ]*\)|FSTYPE=ext4|" $1/etc/initramfs-tools/initramfs.conf
